from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from utils.tooljwt import tool
from rest_framework.response import Response
from user import models
import jwt
import datetime

class JWTAuthenticationss(BaseAuthentication):
  def authenticate(self, request):
      #获取token
      tokendata=request.META.get('HTTP_AUTHORIZATION',None)
      #print(tokendata)
      if tokendata:
          #截取
          token=tokendata.split(' ')[1]
          #解码 然后拿到用户id去验证
          try:
              userdata = tool.checktoken(token)
              user=models.User.objects.get(id=userdata['userid'])
              expiration = userdata.get('exp')
              #print(datetime.datetime.fromtimestamp(expiration))
              return user,token
          except jwt.ExpiredSignatureError:
              raise AuthenticationFailed('token已过期')
          except jwt.InvalidTokenError:
              raise AuthenticationFailed('无效token')
      else:
          return None,None
      # tokendata=request.META.get('HTTP_AUTHORIZATION',None)
      # if tokendata:
      #     #截取
      #     token=tokendata.split(' ')[1]
      #     #解码 然后拿到用户id去验证
      #     try:
      #         userdata = tooljwt.checktoken(token)
      #         if "userid" in userdata:
      #              userid=userdata['userid']
      #              user=models.UserModel.objects.get(id=userid)
      #              return user,token
      #     except:
      #         raise AuthenticationFailed('无效token')
      # else:
      #     return None,None

  def authenticate_header(self, request):
      return 'Bearer realm="api"'